<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import scanService from '@/api/scan'

const props = defineProps({
  sokect: {
    type: Object,
  },
})
/*
 * 打开弹框
 */
// 确定的时候是否要启动扫描（当没有设置参数，点击扫描文件，会先打开弹窗设置参数，此时保存需要调用开始扫描）
const confirmflag = ref(false)
const dialogVisible = ref<boolean>(false)
const openDialog = (flag = false) => {
  confirmflag.value = flag
  queryScanList()
  dialogVisible.value = true
}

// 获取扫描仪列表
const scanner = ref()
const scannerList = ref<any[]>([])
const queryScanList = () => {
  scanService
    .queryScanList()
    .then((res) => {
      scannerList.value = res.data
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 打开扫描仪参数配置
const openSettings = () => {
  if (!scanner.value) {
    ElMessage.warning('请选择扫描仪')
    return
  }
  const params = {
    scannerName: scanner.value,
  }
  scanService.openSettings(params).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
  })
}

// 保存扫描参数
const save = () => {
  if (!scanner.value) {
    ElMessage.warning('请选择扫描仪')
    return
  }
  const params = {
    scannerName: scanner.value,
  }
  scanService
    .saveScanner(params)
    .then(() => {
      ElMessage.success('保存成功')
      dialogVisible.value = false
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
  if (confirmflag.value) {
    const params = JSON.stringify({
      operationInstructions: 'start',
      data: scanner.value,
    })
    props.sokect.send(params)
    // sokect.value.send(params)
  }
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog v-model="dialogVisible" title="扫描参数" width="600px" :close-on-click-modal="false">
    <div class="scan-select">
      <el-select v-model="scanner">
        <el-option v-for="item in scannerList" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button @click="openSettings">属性</el-button>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.scan-select {
  display: flex;
  flex-wrap: nowrap;
  width: 100%;
  .el-select {
    margin-right: 10px;
    flex: 1;
  }
}
</style>
